package connect4client.commands;

import java.util.List;

import game.Player;
import messages.MatchStartedMessage;
import connect4client.core.GameManager;
import connect4client.core.Invitation;

/**
 * The MatchStarted command.
 * 
 * This command will handle MatchStarted messages.
 */
public class MatchStartedCommand extends Command {

	public MatchStartedCommand(MatchStartedMessage matchStartedMessage) {
		super(matchStartedMessage);
	}


	@Override
	public void execute() {
		GameManager gameManager = controller.getGameManager();
		MatchStartedMessage message = (MatchStartedMessage) this.message;
		Player opponent = this.getNewPlayerList(message.getPlayers());
		Invitation invitation = gameManager.getInvitationByID(message.getInvitationId());

		synchronized (gameManager) {
			gameManager.removeInvitation(message.getInvitationId());
			gameManager.createMatch(message.getMatchId());
		}

		guiMediator.matchStarted(controller.getUser().getPlayer(), opponent, invitation.getGameName(), message.getMatchId(), message.getNextPlayerLogin());
	}


	/**	We want the challenger from the list. 
	 * @param The User´s login
	 */
	public Player getNewPlayerList(List<Player> list) {
		for (Player player : list)
			if (!player.getLogin().equals(controller.getUser().getLogin()))
				return player;

		return null;
	}

}
